package com.capgemini.teamtwo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.capgemini.teamtwo.common.ResponseBean;
import com.capgemini.teamtwo.entity.ProjectInfo;
import com.capgemini.teamtwo.entity.SysUser;
import com.capgemini.teamtwo.entity.dto.SysUserDTO;
import com.capgemini.teamtwo.mapper.SysUserMapper;
import com.capgemini.teamtwo.service.ProjectInfoService;
import com.capgemini.teamtwo.service.SysUserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
 * ClassName:SysUserController <br/>
 * Description:<br/>
 * Date:2022/8/27 14:48 <br/>
 *
 * @author 徐志昂
 */
@Api("人员管理")
@RestController
@RequestMapping("/sysuser")
public class SysUserController extends BaseController{
    @Autowired
    private SysUserService service;
    @Autowired
    private ProjectInfo projectInfo;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Resource
    private ProjectInfoService projectInfoService;


@ApiOperation("分页查询,模糊查询")
@GetMapping("/page")
public ResponseBean<Page> page(int page, int pageSize, String realname, String status, String projectName,String dept,String userJob,String rank,String employmentDate) {
    Page<SysUser> pageInfo = new Page<>(page, pageSize);
    Page<SysUserDTO> dtoPage = new Page<>();
    LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
    //添加查询条件，根据name进行like模糊查询
    queryWrapper.like(realname != null && realname != "", SysUser::getRealname, realname);

    //添加查询条件，根据当前状态进行like模糊查询
    queryWrapper.like(status != null && status != "", SysUser::getStatus, status);

    //添加查询条件，根据当前部门进行查询
    queryWrapper.eq(dept != null && dept != "", SysUser::getDept, dept);

    //添加查询条件，根据当前职位进行查询
    queryWrapper.eq(userJob != null && userJob != "", SysUser::getUserJob, userJob);

    //添加查询条件，根据当前职级进行查询
    queryWrapper.eq(rank != null && rank != "", SysUser::getRank, rank);

    //添加查询条件，根据当前年份进行模糊查询
    if (employmentDate != null && employmentDate != "") {
        queryWrapper.ge(SysUser::getEmploymentDate, employmentDate + "-01-01");
        queryWrapper.le(SysUser::getEmploymentDate, employmentDate + "-12-31");
    }


    service.page(pageInfo, queryWrapper);

    List<SysUser> records = pageInfo.getRecords();

    List<SysUserDTO> list = records.stream().map((item) -> {
        SysUserDTO sysUserDTO = new SysUserDTO();
        //对象拷贝
        BeanUtils.copyProperties(item, sysUserDTO);
        //项目id
        Integer id = item.getProjectId();
        //根据id进行查询
        ProjectInfo projectInfo = projectInfoService.getById(id);
        if (projectInfo != null) {
            //获取项目名称
            String pr = projectInfo.getProjectName();

            sysUserDTO.setProjectName(pr);

        }


        return sysUserDTO;
    }).collect(Collectors.toList());

    if (projectName != null&&projectName!="") {
        List<SysUserDTO> list1 = list.stream().filter(
                SysUserDTO -> projectName.equals(SysUserDTO.getProjectName())
        ).collect(Collectors.toList());
        dtoPage.setRecords(list1);
        if (list1.size() != 0) {

            return ResponseBean.success(dtoPage);
        }
    } else {
        dtoPage.setRecords(list);
        if (list.size() != 0) {

            return ResponseBean.success(dtoPage);
        }


    }
    return ResponseBean.failed("没有相应返回的员工信息");
}

    @ApiOperation("新增用户")
    @PostMapping("/add")
    public ResponseBean<String> add(@RequestBody SysUser sysUser) {
//        电话号码校验（正则表达式）
        String regex = "^((13[0-9])|(14[579])|(15([0-3]|[5-9]))|(16[56])|(17[0-8])|(18[0-9])|(19[1589]))\\d{8}$";
//        邮箱校验（正则表达式）
        String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
//        日期格式校验（正则表达式）
        String timeRegex1 = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|"+
                "((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|"+
                "((0[48]|[2468][048]|[3579][26])00))-02-29)$";
        Boolean a = Pattern.matches(timeRegex1,sysUser.getEmploymentDate());
        if(sysUser.getPhone().matches(regex)&&sysUser.getEmail().matches(check)) {
            if (sysUser.getRealname() != null&&sysUser.getRealname()!="") {


                if (a) {
                    sysUser.setStatus("Bench");
                    sysUser.setCreatTime(LocalDateTime.now());
                    sysUser.setUpdateTime(LocalDateTime.now());
                    service.save(sysUser);
                    return ResponseBean.success("新增成功");
                }else {
                    return ResponseBean.failed("日期格式应该为yyyy-mm-dd");
                }
            }
            else {
                return ResponseBean.failed("姓名不能为空");
            }
        }
        else {
            return ResponseBean.failed("手机号或邮箱格式不正确");
        }




    }

    @ApiOperation("根据id删除用户")
    @DeleteMapping("/delete/{id}")
    public ResponseBean<String> deleteById(@PathVariable("id") Integer id) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.in(SysUser::getId,id);
//        判断该员工的状态是否为On Project
        queryWrapper.eq(SysUser::getStatus,"On Project");

        int count = service.count(queryWrapper);
        if(count>0){
            return ResponseBean.failed("当前员工正在项目不能删除");
        }
        else{

        service.removeById(id);
        return ResponseBean.success("删除成功");
    }
    }

    @ApiOperation("根据id获取用户信息")
    @GetMapping("/get/{id}")
    public ResponseBean<SysUser> get(@PathVariable("id") int id) {
        return ResponseBean.success(service.getById(id));
    }


    @ApiOperation("更新用户信息")
    @PutMapping("/update")
    public ResponseBean<String> update(@RequestBody SysUser sysUser) {

        //        电话号码校验（正则表达式）
        String regex = "^((13[0-9])|(14[579])|(15([0-3]|[5-9]))|(16[56])|(17[0-8])|(18[0-9])|(19[1589]))\\d{8}$";
        //        邮箱校验（正则表达式）
        String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        //        日期格式校验（正则表达式）
        String timeRegex1 = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|"+
                "((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|"+
                "((0[48]|[2468][048]|[3579][26])00))-02-29)$";
        Boolean a = Pattern.matches(timeRegex1,sysUser.getEmploymentDate());
        if(sysUser.getPhone().matches(regex)&&sysUser.getEmail().matches(check)) {
            if (sysUser.getRealname() != null&&sysUser.getRealname()!="") {
                if (a) {

                    sysUser.setUpdateTime(LocalDateTime.now());

                    service.updateById(sysUser);
                    return ResponseBean.success("修改成功");
                }else {
                    return ResponseBean.failed("日期格式应该为yyyy-mm-dd");
                }
            }
            else {
                return ResponseBean.failed("姓名不能为空");
            }
        }
        else {
            return ResponseBean.failed("手机号或邮箱格式不正确");
        }



    }








}